package com.eques.demo

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.database.DevList
import com.eques.database.dao.DevListDao
import com.eques.demo.adapter.RecyleViewAdapter
import com.eques.demo.bind.BindDevActivity
import com.eques.demo.bind.HostActivity
import com.eques.event.EventTotalThread
import com.eques.icvss.core.module.user.BuddyType
import com.eques.service.DoorBellService
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity() {
    private var TAG: String? = MainActivity::class.simpleName
    private var rec_dev_data: RecyclerView? = null
    private var adapter: RecyleViewAdapter? = null
    private var lin_dev: LinearLayout? = null
    private var rel_mine: RelativeLayout? = null
    var list = mutableListOf<DevList>()
    private lateinit var ykDao: DevListDao
    private lateinit var username: String
    private var currentTab = 0 // 0:设备, 1:我的

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        initData()
        initView()
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            Config.EVENT_DEVICE_LIST_REFRESH, Config.EVENT_BDY_LIST->{
                getNewDevList()
            }
        }
    }

    private fun getNewDevList(){
        list.clear()
        CoroutineScope(Dispatchers.IO).launch {
            val flowList = ykDao.getUserBdyList(username)
            list.addAll(flowList)
            runOnUiThread{
//                Log.e(TAG, "has data$list")
                adapter!!.notifyDataSetChanged()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(DoorBellService.icvss!=null) {
            if (!DoorBellService.icvss!!.equesIsLogin()) {
                // 判断用户是否掉线
                userClickReconnection()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this);
    }

    override fun initView() {
        rec_dev_data = findViewById(R.id.rec_dev_data)
        lin_dev = findViewById(R.id.lin_dev)
        rel_mine = findViewById(R.id.rel_mine)
        initRec()
        setupBottomNavigation()
    }

    private fun switchTab(tab: Int) {
        if (currentTab == tab) return

        currentTab = tab
        updateBottomNavState(tab)
        updateContent(tab)
    }

    private fun updateBottomNavState(tab: Int) {
        // 设备tab
        val deviceIndicator = findViewById<View>(R.id.indicator_device)
        val deviceIcon = findViewById<ImageView>(R.id.iv_device)
        val deviceText = findViewById<TextView>(R.id.tv_device)

        // 我的tab
        val mineIndicator = findViewById<View>(R.id.indicator_mine)
        val mineIcon = findViewById<ImageView>(R.id.iv_mine)
        val mineText = findViewById<TextView>(R.id.tv_mine)

        if (tab == 0) {
            // 设备tab选中状态
            deviceIndicator.visibility = View.VISIBLE
            deviceIcon.setColorFilter(ContextCompat.getColor(this, R.color.bottom_nav_selected))
            deviceText.setTextColor(ContextCompat.getColor(this, R.color.bottom_nav_selected))

            // 我的tab未选中状态
            mineIndicator.visibility = View.GONE
            mineIcon.setColorFilter(ContextCompat.getColor(this, R.color.bottom_nav_normal))
            mineText.setTextColor(ContextCompat.getColor(this, R.color.bottom_nav_normal))
        } else {
            // 设备tab未选中状态
            deviceIndicator.visibility = View.GONE
            deviceIcon.setColorFilter(ContextCompat.getColor(this, R.color.bottom_nav_normal))
            deviceText.setTextColor(ContextCompat.getColor(this, R.color.bottom_nav_normal))

            // 我的tab选中状态
            mineIndicator.visibility = View.VISIBLE
            mineIcon.setColorFilter(ContextCompat.getColor(this, R.color.bottom_nav_selected))
            mineText.setTextColor(ContextCompat.getColor(this, R.color.bottom_nav_selected))
        }
    }

    private fun updateContent(tab: Int) {

        if (tab == 0) {
            lin_dev?.visibility = View.VISIBLE
            rel_mine?.visibility = View.GONE
        } else {
            lin_dev?.visibility = View.GONE
            rel_mine?.visibility = View.VISIBLE
        }
    }

    private fun setupBottomNavigation() {
        updateBottomNavState(currentTab)
    }

    /**
     * 初始化RecyclerView控件的函数
     * 此函数用于设置RecyclerView的布局管理器，适配器，并将数据源绑定到RecyclerView上
     */
    private fun initRec() {
        // 获取服务实例中的数据列表作为RecyclerView的数据源
        CoroutineScope(Dispatchers.IO).launch {
            val flowList = ykDao.getUserBdyList(username)
            list.addAll(flowList)
        }
        // 创建一个LinearLayoutManager实例，用于RecyclerView的项布局排列
        val linearLayoutManager = LinearLayoutManager(this)
        // 设置布局管理器的方向为垂直
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        // 为RecyclerView设置布局管理器
        rec_dev_data?.layoutManager = linearLayoutManager
        // 创建RecyclerView的适配器，传入数据列表和上下文
        adapter = RecyleViewAdapter(list, this)
        // 为RecyclerView设置适配器
        rec_dev_data?.adapter = adapter
    }

    fun viewClick(view: View) {
        when (view.id) {
            R.id.rel_add_dev -> {
                val intent = Intent(this, BindDevActivity::class.java)
                intent.putExtra(Config.ADDING_DEVICES_TYPE,BuddyType.TYPE_WIFI_DOOR_WS2)
                startActivity(intent)
            }

            R.id.btn_exit -> {
                DoorBellService.icvss!!.equesUserLogOut()
                preference.putBoolean(Config.LOGIN_STATE, false)
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
                finish()
            }

            R.id.ll_device -> {
                switchTab(0)
            }

            R.id.ll_mine -> {
                switchTab(1)
            }

            R.id.rel_add_lock_dev->{
                val intent = Intent(this, BindDevActivity::class.java)
                intent.putExtra(Config.ADDING_DEVICES_TYPE,BuddyType.TYPE_WIFI_DOOR_VM5)
                startActivity(intent)
            }

            R.id.rel_host_dev->{
                val intent = Intent(this, HostActivity::class.java)
                startActivity(intent)
            }
        }
    }

    override fun initData() {
        ykDao = BaseAppApplication.instance!!.getYkDao(this)
        username = preference.getString(Config.EQUES_USER_NAME)!!
    }
}